import { createRouter, createWebHistory } from 'vue-router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/stores/modules/user'
// import { storeToRefs } from 'pinia'

import LayoutsIndex from '@/views/layouts/index.vue'
import NotFound from '@/views/404.vue'
import type { RouteRecordRaw } from 'vue-router'

// 初始化子路由
let childrenRoutes: RouteRecordRaw[] = [
  {
    path: '',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    meta: {
      title: '首页'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layouts',
      component: LayoutsIndex,
      children: childrenRoutes
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: '404',
      component: NotFound,
      meta: {
        title: '错误页'
      }
    }
  ]
})

// 前置路由守卫钩子
router.beforeEach((to, from, next) => {
  // 显示全屏页面加载进度条
  nprogress.start()

  // 没有登录 强制登录页
  const userStore = useUserStore()
  if (to.path !== '/login' && !userStore.token) {
    return next({ name: 'login' })
  }

  // 已登录 防止重复登录
  if (userStore.token && to.path === '/login') {
    return next({ path: from.path })
  }

  // 根据路由中的 meta 动态设置页面标题
  const title = (to.meta.title ? to.meta.title : '') + ' 后台管理系统'
  document.title = title

  // 在用户登录后生成动态路由
  if (userStore.token && !userStore.routesGenerated) {
    const { userInfo } = storeToRefs(userStore)
    const menus = userInfo.value?.menus
    if (menus) {
      menus.forEach((menu1: any) => {
        menu1.child.forEach((menu: any) => {
          // 分割frontpath
          const frontpath = menu.frontpath.split('/')
          let name = ''
          if (frontpath[2]) {
            name = frontpath[1] + frontpath[2].charAt(0).toUpperCase() + frontpath[2].slice(1)
          }
          router.addRoute('layouts', {
            path: menu.frontpath,
            name: name,
            component: () => import(`@/views/${frontpath[1]}/${frontpath[2]}.vue`),
            meta: {
              title: menu.name
            }
          })
        })
      })
      userStore.routesGenerated = true
    }
  }

  next()
})

// 后置路由守卫钩子
router.afterEach((to, from) => {
  // 隐藏全屏页面加载进度条
  nprogress.done()
})

export default router
